﻿using Digitalmes.Core.Domain.Eitites;
using Digitalmes.Core.Domain.Repositories;

namespace Digitalmes.Core.Services.Impl;

internal sealed class CounterService(IRepository<Counter> repo) : ICounterService
{
    public async Task<int> GetCurrentAsync(string code)
    {
        var counter = await repo.FirstOrDefaultAsync(m => m.Code == code).ConfigureAwait(false);
        return counter?.Number ?? 0;
    }

    public async Task<int> IncrementOrCreateAsync(string code, string? createName = "")
    {
        var counter = await repo.FirstOrDefaultAsync(m => m.Code == code).ConfigureAwait(false);
        if (counter == null)
        {
            counter = new Counter
            {
                Code = code,
                Name = createName,
                Number = 1,
            };
            await repo.InsertAsync(counter).ConfigureAwait(false);
        }
        else
        {
            counter.Number += 1;
            await repo.UpdateAsync(counter, m => new
            {
                m.Number,
            }).ConfigureAwait(false);
        }

        return counter.Number;
    }

    public async Task ResetAsync(string code)
    {
        var counter = await repo.FirstOrDefaultAsync(m => m.Code == code).ConfigureAwait(false);
        if (counter != null)
        {
            counter.Number = 0;
            await repo.UpdateAsync(counter, m => new
            {
                m.Number,
            }).ConfigureAwait(false);
        }
    }
}
